package com.starblink.library.widget.novice_guide.control

import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.RectF
import android.text.method.ScrollingMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.appbar.AppBarLayout
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.constant.RefreshState
import com.starblink.android.basic.appupdate.AppUpdateManager
import com.starblink.android.basic.databinding.AddVMainAppUpdateBinding
import com.starblink.android.basic.databinding.LayoutPopBaseHollowBinding
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.dp
import com.starblink.android.basic.ext.enableCorner
import com.starblink.android.basic.ext.gone
import com.starblink.android.basic.ext.isVisible
import com.starblink.android.basic.ext.locationOnScreen
import com.starblink.android.basic.ext.locationOnWindow
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.guide.SkNoviceManage
import com.starblink.android.basic.guide.bean.SkGuideBusConfig
import com.starblink.android.basic.guide.bean.SkGuideEnum
import com.starblink.android.basic.sensorsdata.exposure.isInScreenGuide
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.CoroutineUpdateTask
import com.starblink.android.basic.util.PopupWindowUtils
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.CollectProductEvent
import com.starblink.basic.apollo.ext.ApolloValSetExt.apolloValue
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.library.widget.novice_guide.branddetails.BrandDetailsFollowPopView
import com.starblink.library.widget.novice_guide.home.FirstProductCollPop
import com.starblink.library.widget.novice_guide.home.HomeBrandPopView
import com.starblink.library.widget.novice_guide.home.HomeBrandPopViewNoData
import com.starblink.library.widget.novice_guide.home.HomeDiscountPopView
import com.starblink.rocketreserver.FetchLatestVersionQuery
import kotlinx.coroutines.delay

object GuidePopStatusControl {

    //引导的轮询队列
    private var taskGuideMap = hashMapOf<String, CoroutineUpdateTask>()
    private var showGuideMap = hashMapOf<String, Boolean>()

    var homeDiscountHasData = false

    private fun cancelTask(tag: String) {
        showGuideMap[tag] = true
        taskGuideMap[tag]?.cancel()
        taskGuideMap.remove(tag)
    }

    /**
     * 折扣引导
     * appBar 控制滚动
     * refreshLayout 判断滚动是否停止
     * guideType 当前界面类型 tag
     * tarView 要转成bitmap的view
     * bootView tarView的父视图
     */
    fun popDiscountGuide(
        appBar: AppBarLayout,
        refreshLayout: SmartRefreshLayout,
        guideType: String,
        screenView: View,
        tarView: View,
        bootView: ViewGroup
    ) {
        FlowBus.with<Boolean>(SkGuideBusConfig.HOME_FRG_DISCOUNT_V2_NAME).register(tarView) {
            if (taskGuideMap[guideType] == null) {
                taskGuideMap[guideType] = CoroutineUpdateTask()
                taskGuideMap[guideType]?.scheduleUpdate(500, action = {
                    if (showGuideMap[guideType] != true && UserDataCenter.currentIndex == 0 && refreshLayout.state == RefreshState.None && tarView.isInScreenGuide()) {
                        cancelTask(guideType)
                        screenView.post {
                            //获取布局位置 相对于整个屏幕
                            getHollowRectF(screenView)
                                ?.let { rectF ->
                                    //94 顶部搜索框高度 | 6 CoordinatorLayout marginTop | 8 折扣布局marginTop | 8 为了好看，在本布局已经到达顶部的时候往下滑8
                                    homeScrollToTopOffset(
                                        appBar,
//                                        rectF.top.toInt() - (94 + 6 + 8 + 8).dp2px()
                                        rectF.top.toInt() - (94 + 8).dp2px()
                                    )
                                    HomeDiscountPopView.pushPopWindow(
                                        tarView,
                                        bootView,
                                        dismissCallBack = {
                                            SkNoviceManage.hasPopGuide(SkGuideEnum.HOME_FRG_DISCOUNT_V2)
                                            //刷下一个
                                            FlowBus.boolFlowBusNotify(FlowConst.HOME_GUIDE_NEXT)
                                        }
                                    )
                                }
                        }
                    }
                })
            }
        }
    }

    /**
     * brand引导
     */
    fun popBrandGuide(
        appBar: AppBarLayout,
        refreshLayout: SmartRefreshLayout,
        guideType: String,
        screenView: View,
        tarView: View,
        bootView: ViewGroup
    ) {
        FlowBus.with<Boolean>(SkGuideBusConfig.HOME_FRG_BRAND_V2_NAME).register(tarView) {
            if (taskGuideMap[guideType] == null) {
                taskGuideMap[guideType] = CoroutineUpdateTask()
                taskGuideMap[guideType]?.scheduleUpdate(500, action = {
                    if (showGuideMap[guideType] != true && UserDataCenter.currentIndex == 0 && refreshLayout.state == RefreshState.None && tarView.isInScreenGuide()) {
                        cancelTask(guideType)
                        if (homeDiscountHasData) {
                            HomeBrandPopView.pushPopWindow(
                                tarView,
                                bootView,
                                dismissCallBack = {
                                    SkNoviceManage.hasPopGuide(SkGuideEnum.HOME_FRG_BRAND_V2)
                                    //刷下一个
                                    FlowBus.boolFlowBusNotify(FlowConst.HOME_GUIDE_NEXT)
                                }
                            )
                        } else {
                            HomeBrandPopViewNoData.pushPopWindow(
                                tarView,
                                bootView,
                                dismissCallBack = {
                                    SkNoviceManage.hasPopGuide(SkGuideEnum.HOME_FRG_BRAND_V2)
                                    //刷下一个
                                    FlowBus.boolFlowBusNotify(FlowConst.HOME_GUIDE_NEXT)
                                }
                            )
                        }

//                        screenView.post {
//                            //获取布局位置 相对于整个屏幕
//                            getHollowRectF(screenView)
//                                ?.let { rectF ->
//                                    //有数据 引导箭头出现在上边 没数据 在下边
//
//                                }
//                        }
                    }
                })
            }
        }
    }


    fun popBrandDetailsFollowGuide(
        guideType: String,
        tarView: View,
        bootView: ViewGroup
    ) {
        if (SkNoviceManage.canShowGuide(SkGuideEnum.BRAND_DETAIL_BRAND_FOLLOW)) {
            if (taskGuideMap[guideType] == null) {
                taskGuideMap[guideType] = CoroutineUpdateTask()
                taskGuideMap[guideType]?.scheduleUpdate(500, action = {
                    if (showGuideMap[guideType] != true && tarView.isInScreenGuide()) {
                        cancelTask(guideType)
                        BrandDetailsFollowPopView.pushPopWindow(
                            tarView,
                            bootView,
                            dismissCallBack = {
                                SkNoviceManage.hasPopGuide(SkGuideEnum.BRAND_DETAIL_BRAND_FOLLOW)
                            }
                        )
                    }
                })
            }
        }
    }


    private var homeBehavior: Any? = null
    fun homeScrollToTopOffset(appBar: AppBarLayout, offset: Int) {
        if (homeBehavior == null) {
            homeBehavior = (appBar.layoutParams as CoordinatorLayout.LayoutParams).behavior
        }
        if (homeBehavior is AppBarLayout.Behavior) {
            (homeBehavior as AppBarLayout.Behavior).topAndBottomOffset = -offset
        }
    }


    fun feedsProductPopGuide(
        spmPageValue: Int = 0,
        dataPosition: Int,
        refreshLayout: SmartRefreshLayout? = null,
        recyclerView: RecyclerView,
        screenView: View,
        tarView: View,
        bootView: ViewGroup,
        guideType: String,
        asHomePage: Boolean = false
    ) {
        if (dataPosition == 0 && SkNoviceManage.canShowGuide(SkGuideEnum.HOME_FRG_1_PRODUCT_COLL_V2)) {
            recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {

                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    if (!asHomePage && dy == 1 && showGuideMap[guideType] != true && screenView.isInScreenGuide()) {
                        if (SkNoviceManage.canShowGuide(SkGuideEnum.HOME_FRG_1_PRODUCT_COLL_V2)) {
                            cancelTask(guideType)
                            tarView.post {
                                FirstProductCollPop.pop(
                                    tarView,
                                    bootView,
                                    spmPage = spmPageValue
                                )
                            }
                        }
                    }
                }

                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    //停止滑动
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        if (showGuideMap[guideType] != true && screenView.isInScreenGuide()) {
                            cancelTask(guideType)
                            tarView.post {
                                FirstProductCollPop.pop(
                                    tarView,
                                    bootView,
                                    spmPage = spmPageValue
                                )
                            }
                        }
                    }
                }
            })


            if (!asHomePage) {
                FlowBus.with<Boolean>(SkGuideBusConfig.HOME_FRG_1_PRODUCT_V2_NAME)
                    .register(tarView) { event ->
                        if (showGuideMap[guideType] != true && SkNoviceManage.canShowGuide(
                                SkGuideEnum.HOME_FRG_1_PRODUCT_COLL_V2
                            )
                        ) {
                            recyclerView.scrollBy(0, 1)
                        }
                    }

                if (taskGuideMap[guideType] == null) {
                    taskGuideMap[guideType] = CoroutineUpdateTask()
                    taskGuideMap[guideType]?.scheduleUpdate(500, action = {
                        if (showGuideMap[guideType] != true) {
                            FlowBus.boolFlowBusNotify(SkGuideBusConfig.HOME_FRG_1_PRODUCT_V2_NAME)
                        }
                    })
                }
            }
        }
    }


    @SuppressLint("ClickableViewAccessibility")
    inline fun pushPopWindow(
        context: Activity,
        parent: ViewGroup,
        updateInfo: FetchLatestVersionQuery.FetchLatestVersion,
        crossinline dismissCallBack: () -> Unit
    ) {
        getHollowRectF(parent, true)?.let { rectF ->
            val bd = LayoutPopBaseHollowBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
            bd.popBaseHollow.setRect(RectF(0f, 0f, 0f, 0f), 0f)

            // 更新弹窗
            val toastLay =
                AddVMainAppUpdateBinding.inflate(LayoutInflater.from(context), bd.root, false)

            bd.root.addView(toastLay.root)
            val pp = PopupWindowUtils.getNormalPopWindow(
                context = context,
                anchorView = bd.root,
                parent = parent,
                anchorRect = null,
                dismissClickView = null,
                dismissCallBack = { dismissCallBack() })

            // 设置更新弹窗
            toastLay.tvTitle.text = updateInfo.updateTitle
            toastLay.tvContent.text = updateInfo.updateMessage
            toastLay.tvContent.movementMethod = ScrollingMovementMethod.getInstance()

            // 强制更新，不显示Not Now按钮
            if (updateInfo.forceUpdate) {
                toastLay.btnNotNow.gone()
            } else {
                toastLay.btnNotNow.run {
                    visible()
                    click {
                        pp.dismiss()
                        dismissCallBack()
                    }
                    enableCorner(8.dp)
                }

            }
            toastLay.btnUpdate.run {
                click {
                    // 更新APP
                    AppUpdateManager.startGooglePlay()
                    // 强制更新，不关闭弹窗，必须更新APP
                    if (!updateInfo.forceUpdate) {
                        pp.dismiss()
                        dismissCallBack()
                    }
                }
                enableCorner(8.dp)
            }

        }
    }


    private const val DEFAULT_PADDING = 6f

    /**
     * locationOnWindow 如果被隐藏部分，也能拿到全部的rectF
     */
    fun getHollowRectF(
        anchorView: View?,
        padding: Boolean = false,
        paddingValue: Float = DEFAULT_PADDING
    ): RectF? {

        if (anchorView == null) {
            return null
        }

        val location = anchorView.locationOnScreen()

        val delta = if (padding) paddingValue else 0f


        return if (location == null) {
            null
        } else {
            val w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            val h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            anchorView.measure(w, h)
            val height: Int = anchorView.measuredHeight
            val width: Int = anchorView.measuredWidth


            RectF(
                location[0].toFloat() - delta,
                location[1].toFloat() - delta,
                location[0] + delta + width,
                location[1] + delta + height
            )
        }
    }

    /**
     * locationOnWindow 如果被隐藏部分，只能拿到部分的rectF
     */
    fun getHollowRectFWindow(
        anchorView: View?
    ): RectF? {

        if (anchorView == null) {
            return null
        }

        val location = anchorView.locationOnWindow()



        return if (location == null) {
            null
        } else {
            val w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            val h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            anchorView.measure(w, h)
            val height: Int = anchorView.measuredHeight
            val width: Int = anchorView.measuredWidth


            RectF(
                location[0].toFloat(),
                location[1].toFloat(),
                location[0] + width.toFloat(),
                location[1] + height.toFloat()
            )
        }
    }


}